package cn.exrick.xboot.modules.system.controller;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.ServeUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.socketXTB.monitor.server.ServerHeart;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.AccessControl.entity.AccessControlUser;
import cn.exrick.xboot.modules.AccessControl.service.IAccessControlUserService;
import cn.exrick.xboot.modules.portalConfig.service.IPortalConfigService;
import cn.exrick.xboot.modules.system.entity.System;
import cn.exrick.xboot.modules.system.service.ISystemService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "子系统的快捷入口信息管理接口")
@RequestMapping("/xboot/system")
@Transactional
public class SystemController {

    @Autowired
    private ISystemService iSystemService;

    @Autowired
    private IPortalConfigService iPortalConfigService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IAccessControlUserService iAccessControlUserService;

    @Value("${server.port}")
    private String port;
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<System> get(@PathVariable String id) {
        System system = iSystemService.getById(id);
        return new ResultUtil<System>().setData(system);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<System>> getAll() {

        List<System> list = iSystemService.list();
        return new ResultUtil<List<System>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<System>> getByPage(@ModelAttribute PageVo page) {

        IPage<System> data = iSystemService.page(PageUtil.initMpPage(page));
        return new ResultUtil<IPage<System>>().setData(data);
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑或更新数据")
    public Result<System> saveOrUpdate(@ModelAttribute System system) {
        system.setUpdateTime(new Date());
        if (iSystemService.saveOrUpdate(system)) {
            return new ResultUtil<System>().setData(system);
        }
        return new ResultUtil<System>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids) {
        List<AccessControlUser> acuList=new ArrayList<>();
        for (String id : ids) {
              iSystemService.removeById(id);
             acuList.add(new AccessControlUser(id) );
        }
        iAccessControlUserService.delAccessControlBySys(acuList);
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }

    @RequestMapping(value = "/selectSystemPageVoMap", method = RequestMethod.GET)
    @ApiOperation(value = "条件获取快捷入口信息")
    public Result<IPage<System>> selectSystemPageVoMap(@ModelAttribute Page page, @Param("sname") String sname, @Param("url") String url) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (sname != null && !sname.equals("") && sname.length() != 0 && !sname.trim().isEmpty()) {
            map.put("sys_name", sname);
        }
        if (url != null && !url.equals("") && url.length() != 0 && !url.trim().isEmpty()) {
            map.put("url", url);
        }

        IPage<System> systemIPage = iSystemService.selectSystemPageVoMap(page, map);

        return new ResultUtil<IPage<System>>().setData(systemIPage);
    }

    @RequestMapping(value = "/addSystem", method = RequestMethod.POST)
    @ApiOperation(value = "新增保存数据")
    public Result<Object> addSystem(@ModelAttribute System system) {
        system.setCreateTime(new Date());
        system.setUpdateTime(new Date());
        system.setStatus(0);
        boolean save = iSystemService.save(system);
        if (save) {
            return new ResultUtil<Object>().setSuccessMsg("添加成功");
        }
        return new ResultUtil<Object>().setErrorMsg("添加失败");
    }

    /**
     * ADD 快捷入口的禁用启用 begin
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/disable/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "禁用某快捷入口")
    public Result<Object> disable(@PathVariable String id) {
        System sys = iSystemService.getById(id);
        if (sys == null) {
            return new ResultUtil<Object>().setErrorMsg("通过Id获取失败");
        }
        sys.setStatus(CommonConstant.TY_DISABLE);
        boolean b = iSystemService.updateById(sys);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/enable/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "启用某快捷入口")
    public Result<Object> enable(@PathVariable String id) {
        System sys = iSystemService.getById(id);
        if (sys == null) {
            return new ResultUtil<Object>().setErrorMsg("通过Id获取失败");
        }
        sys.setStatus(CommonConstant.TY_NORMAL);
        boolean b = iSystemService.updateById(sys);
        return new ResultUtil<Object>().setData(null);
    }

    /**
     * ADD 快捷入口的禁用启用 end
     */
    @RequestMapping(value = "/getSystemAPP", method = RequestMethod.GET)
    @ApiOperation(value = "获取APP快捷入口")
    public Result<List<System>> getSystemAPP(HttpServletRequest request) {

        String headerToken = request.getHeader(SecurityConstant.HEADER);
        String v = stringRedisTemplate.opsForValue().get(SecurityConstant.APP_TOKEN_PRE + headerToken);
        if (v == null || v == ""){
            return new ResultUtil<List<System>>().setErrorMsg(401,"登录已失效，请重新登录!");
        }
        List<System> systems = iSystemService.selectSystemAPP();

        for (System s:systems ) {
            s.setInfoID(null);
        }
        return new ResultUtil<List<System>>().setData(systems);
    }

    @RequestMapping(value = "/Upload", method = RequestMethod.POST)
    @ApiOperation(value = "快捷入口的图片上传")
    public Result<Object> upload(@RequestParam(required = false) MultipartFile file,
                                 @RequestParam(required = false) String base64,
                                 HttpServletRequest request) {
        String message;
        InputStream inputStream;
        //写入静态资源成功时报标识符
        boolean flag = false;
        String newId = null;
        String IP="127.0.0.1";
        java.lang.System.out.println("新闻文件上传");
        try {
            /*InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
             IP = address.getHostAddress();//192.168.0.121*/
            IP = ServeUtil.getInet4Address();
            java.lang.System.out.println("ip地址:"+IP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //文件名称
        String fileName = file.getOriginalFilename();
        java.lang.System.out.println("文件名字：" + fileName);
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取上传地址
        String path= iPortalConfigService.selectPortalConfigByKey("upload").getValue();
        File uploadPath = new File(path);
        if (!uploadPath.exists()) {
            //创建目录
            uploadPath.mkdir();
        }
        // 新文件名（唯一）
        String newFileName = new Date().getTime() + "." + suffix;
        java.lang.System.out.println("新文件名：" + newFileName);
        // 调用FileItem的write()方法，写入文件
        File newFile = new File(path + newFileName);
        log.info("newFile.getAbsolutePath()" + newFile.getAbsolutePath());
        //将图片存入文件夹
        File targetFile = new File(uploadPath, newFileName);
        try {
            file.transferTo(targetFile);
            message = "图片上传成功";
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
            message = "图片上传失败";
        }
        //拼接图片访问链接
        //newFileName
        //http://10.2.24.14:8899/portalImage/Rectangle-path@3x(5).png
        /**
         *  njp 20200224获取资源服务器的port的改造 begin
         */
        String  fileProjectPort =ServeUtil.getFilrProject();
        /**
         *  njp 20200224 获取资源服务器的port的改造 end
         */
        String imgUrl="http://"+IP+":"+fileProjectPort+CommonConstant.IMAGE_PATH+newFileName;
        log.info( "图片访问地址"+ imgUrl);
        System sys=new System();
        sys.setImageUrl(imgUrl);
        return new ResultUtil<Object>().setData(sys);
    }

    @RequestMapping(value = "/deltest", method = RequestMethod.DELETE)
    @ApiOperation(value = "测试删除服务")
    public Result<Object> deltest() {
        System sys=new System();
        sys.setId("167074391371288576");
        sys.setModuleName("FD");
        new ServerHeart().delSys(sys);
        return new ResultUtil<Object>().setData(null);
    }
    @RequestMapping(value = "/addtest", method = RequestMethod.DELETE)
    @ApiOperation(value = "测试添加服务")
    public Result<Object>addtest() {
        System sys=new System();
        sys.setId("167074391371288576");
        sys.setModuleName("FD");
        //new ServerHeart().delSys(sys);
        new ServerHeart().addSys(sys);
        return new ResultUtil<Object>().setData(null);
    }
}
